﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GtaAPIClient.CounterComprehensiveService;
using GtaAPIClient.XhDoOrderService;
using GtaAPIClient.XhDoQueryService;
using zbus;

namespace GtaAPIClient
{
    class IfManage
    {
        WcfService wcfService = null;
        ServiceConsole.UpdateTextDelegate delg = null;

        public IfManage()
        {
            wcfService = new WcfServiceImpl();
        }

        public IfManage(ServiceConsole.UpdateTextDelegate delg)
        {
            this.delg = delg;
            delg.BeginInvoke("IfManage服务初始化成功", null, null);
            wcfService = new WcfServiceImpl();
        }

        public void test()
        {
            //getIfCapital("010001030906", "4IG7HVe9JcA="); 

            doIfOrder("010001295206", "IF1307", 2, 2, 4, 10, 1, 0, "", "111", "S4co6ZKWVbs=");
        }

        [Remote("IfTest")]
        public string IfTest()
        {
            return "test ok";
        }

        [Remote("ifDoOrder")]
        public OrderResponse doIfOrder(string capitalAccount, string stockCode, int buySell, int openClose,
                float orderQuty, float orderPrice, int unit, int marketPrice, string PortfoliosId, string traderId, string traderPassword)
        {
            try
            {
                XhDoOrderService.StockIndexFuturesOrderRequest futuresorder = new XhDoOrderService.StockIndexFuturesOrderRequest();
                futuresorder.BuySell = buySell == 1 ? XhDoOrderService.TypesTransactionDirection.Buying : XhDoOrderService.TypesTransactionDirection.Selling;
                futuresorder.Code = stockCode;
                futuresorder.FundAccountId = capitalAccount;
                futuresorder.OrderAmount = orderQuty;
                futuresorder.OrderPrice = orderPrice;
                futuresorder.OrderUnitType = XhDoOrderService.TypesUnitType.Hand;
                futuresorder.OrderWay = marketPrice == 1 ? XhDoOrderService.GTTypesOrderPriceType.OPTMarketPrice : XhDoOrderService.GTTypesOrderPriceType.OPTLimited;
                futuresorder.PortfoliosId = PortfoliosId;
                futuresorder.TraderId = traderId;
                futuresorder.TraderPassword = traderPassword;

                if (openClose == 1)
                {
                    futuresorder.OpenCloseType = XhDoOrderService.GTTypesFutureOpenCloseType.OpenPosition;
                }
                else
                {
                    if (openClose == 2)
                    {
                        futuresorder.OpenCloseType = XhDoOrderService.GTTypesFutureOpenCloseType.ClosePosition;
                        //检查持仓
                        FuturesHoldConditionFindEntity cond = new FuturesHoldConditionFindEntity();
                        cond.BuySellDirectionId = 3 - buySell;
                        cond.ContractCode = stockCode;
                        int count = 0;
                        int pageNo = 1;
                        int pageSize = 10;
                        string strErrorMessage = "";

                        decimal todayAmount = 0;
                        decimal hisAmount = 0;
                        FuturesHoldFindResultEntity[] res = wcfService.queryIfHold(out count, capitalAccount, traderPassword, cond, pageNo, pageSize, ref strErrorMessage);
                        if (res != null && res.Length > 0)
                        {
                            foreach (FuturesHoldFindResultEntity r in res)
                            {
                                hisAmount += (r.HoldFindResult.HistoryHoldAmount - r.HoldFindResult.HistoryFreezeAmount);
                                todayAmount += (r.HoldFindResult.TodayHoldAmount - r.HoldFindResult.TodayFreezeAmount);
                            }
                        }
                        
                        if (orderQuty <= (float.Parse(hisAmount.ToString()) + float.Parse(todayAmount.ToString())))
                        {
                            if (orderQuty > float.Parse(hisAmount.ToString()))
                            {
                                OrderResponse orderRes1 = new OrderResponse();
                                if (hisAmount > 0)
                                {
                                    futuresorder.OrderAmount = float.Parse(hisAmount.ToString());
                                    futuresorder.OpenCloseType = XhDoOrderService.GTTypesFutureOpenCloseType.ClosePosition;
                                    orderRes1 = wcfService.doIfOrder(futuresorder);
                                }

                                if (todayAmount > 0)
                                {
                                    futuresorder.OrderAmount = orderQuty - float.Parse(hisAmount.ToString());
                                    futuresorder.OpenCloseType = XhDoOrderService.GTTypesFutureOpenCloseType.CloseTodayPosition;
                                    orderRes1 = wcfService.doIfOrder(futuresorder);
                                }
                                return orderRes1;
                            }
                        }
                    }
                    else if (openClose == 3)
                    {
                        futuresorder.OpenCloseType = XhDoOrderService.GTTypesFutureOpenCloseType.CloseTodayPosition;
                    }
                }

                OrderResponse orderRes = wcfService.doIfOrder(futuresorder);
                return orderRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货委托失败" + ex.Message, null, null);
                throw new Exception("股指期货委托失败", ex);
            }
        } 


        [Remote("ifCancelOrder")]
        public CancelOrderResult cancelOrder(string orderId)
        {
            try
            {
                GTTypesOrderStateType ost = new GTTypesOrderStateType();
                string message = "";
                bool isSuccess = wcfService.cancelIfOrder(orderId, ref message, out ost);
                CancelOrderResult res = new CancelOrderResult();
                res.IsSucess = isSuccess;
                res.Message = message;
                res.OrderStatus = (int)ost;
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货委托撤单失败" + ex.Message, null, null);
                throw new Exception("股指期货委托撤单失败", ex);
            }
        }

        [Remote("ifGetMaxOrderAmount")]
        public int getIfMaxOrderAmount(string TraderId, float OrderPrice, string Code, int marketPrice)
        {
            try
            {
                string outMessage = "";
                CounterComprehensiveService.GTTypesOrderPriceType orderPriceType = marketPrice == 1 ?
                    CounterComprehensiveService.GTTypesOrderPriceType.OPTMarketPrice : CounterComprehensiveService.GTTypesOrderPriceType.OPTLimited;
                long res = wcfService.getIfMaxOrderAmount(out outMessage, TraderId, OrderPrice, Code, orderPriceType);
                return (int)res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货获取最大委托数量失败" + ex.Message, null, null);
                throw new Exception("股指期货获取最大委托数量失败", ex);
            }
        }


        [Remote("ifGetMaxCloseAmount")]
        public int getIfMaxCloseAmount(string capitalAccount, string strPassword, string stockCode, int buySellFlag)
        {
            FuturesHoldConditionFindEntity cond = new FuturesHoldConditionFindEntity();
            cond.BuySellDirectionId = buySellFlag;
            cond.ContractCode = stockCode;

            int count = 0;
            int pageNo = 1;
            int pageSize = 10;
            string strErrorMessage = "";

            try
            {
                Int32 max = 0;
                FuturesHoldFindResultEntity[] res = wcfService.queryIfHold(out count, capitalAccount, strPassword, cond, pageNo, pageSize, ref strErrorMessage);
                if (res == null || res.Length <= 0)
                {
                    return max;
                }

                foreach (FuturesHoldFindResultEntity r in res)
                {
                    max += r.AvailableTotalAmount;
                }
                return max;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货查询可用数失败" + ex.Message, null, null);
                throw new Exception("股指期货查询可用数失败", ex);
            }
        }


        [Remote("ifGetTradeFee")]
        public decimal getIfTradeFee(string capitalAccount, string stockCode, int buySell, int openClose,
                float orderQuty, float orderPrice, int unit, int marketPrice, string PortfoliosId, string traderId, string traderPassword)
        {
            try
            {
                CounterComprehensiveService.StockIndexFuturesOrderRequest futuresorder = new CounterComprehensiveService.StockIndexFuturesOrderRequest();
                futuresorder.BuySell = buySell == 1 ? CounterComprehensiveService.TypesTransactionDirection.Buying : CounterComprehensiveService.TypesTransactionDirection.Selling;
                futuresorder.Code = stockCode;
                futuresorder.FundAccountId = capitalAccount;
                futuresorder.OrderAmount = orderQuty;
                futuresorder.OrderPrice = orderPrice;
                futuresorder.OrderUnitType = CounterComprehensiveService.TypesUnitType.Hand;
                futuresorder.OrderWay = marketPrice == 1 ? CounterComprehensiveService.GTTypesOrderPriceType.OPTMarketPrice : CounterComprehensiveService.GTTypesOrderPriceType.OPTLimited;
                futuresorder.PortfoliosId = PortfoliosId;
                futuresorder.TraderId = traderId;
                futuresorder.TraderPassword = traderPassword;
                if (openClose == 1)
                {
                    futuresorder.OpenCloseType = CounterComprehensiveService.GTTypesFutureOpenCloseType.OpenPosition;
                }
                else if (openClose == 2)
                {
                    futuresorder.OpenCloseType = CounterComprehensiveService.GTTypesFutureOpenCloseType.ClosePosition;
                }
                else if (openClose == 3)
                {
                    futuresorder.OpenCloseType = CounterComprehensiveService.GTTypesFutureOpenCloseType.CloseTodayPosition;
                }
                
                string errMsg = "";
                decimal fee = wcfService.getIfTradeFee(out errMsg, futuresorder);
                if (!string.IsNullOrEmpty(errMsg))
                {
                    fee = 0M;
                }
                return fee;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("计算股指期货手续费失败" + ex.Message, null, null);
                throw new Exception("计算股指期货手续费失败", ex);
            }
        } 
        

        [Remote("ifGetTodayOrder")]
        public TodayEntrustResult getIfTodayOrder(string capitalAccount, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            FuturesEntrustConditionFindEntity cond = new FuturesEntrustConditionFindEntity();
            try
            {
                TodayEntrustResult pagingRes = new TodayEntrustResult();
                QH_TodayEntrustTableInfo[] res = wcfService.queryIfOrder(out total, capitalAccount, pwd, cond, pageNo, pageSize, ref errorMsg);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                pagingRes.Total = total;
                TodayEntrust[] tmp = new TodayEntrust[res.Length];
                int i = 0;
                foreach (QH_TodayEntrustTableInfo e in res)
                {
                    TodayEntrust m = new TodayEntrust();
                    m.EntrustAmount = e.EntrustAmount;
                    m.EntrustNumber = e.EntrustNumber;
                    m.EntrustPrice = e.EntrustPrice;
                    m.EntrustTime = e.EntrustTime.ToString();
                    m.TradeAmount = e.TradeAmount;
                    m.TradeAveragePrice = e.TradeAveragePrice;
                    m.CancelAmount = e.CancelAmount;
                    m.IsMarketValue = e.IsMarketValue;
                    m.OrderMessage = e.OrderMessage;
                    m.OrderStatusId = e.OrderStatusId;
                    m.BuySellTypeId = e.BuySellTypeId;
                    m.SpotCode = e.ContractCode;
                    m.CloseFloatProfitLoss = e.CloseFloatProfitLoss;
                    m.CloseMarketProfitLoss = e.CloseMarketProfitLoss;
                    m.OpenCloseTypeId = e.OpenCloseTypeId;
                    m.CancelLogo = e.CancelLogo == true ? 1 : 0;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货查询当日委托失败" + ex.Message, null, null);
                throw new Exception("股指期货查询当日委托失败", ex);
            }
        }

        [Remote("ifGetHistoryOrder")]
        public TodayEntrustResult getIfHistoryOrder(string capitalAccount, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            FuturesEntrustConditionFindEntity cond = new FuturesEntrustConditionFindEntity();
            try
            {
                TodayEntrustResult pagingRes = new TodayEntrustResult();
                QH_HistoryEntrustTableInfo[] res = wcfService.queryIfHistoryOrder(out total, capitalAccount, pwd, cond, pageNo, pageSize, ref errorMsg);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                pagingRes.Total = total;
                TodayEntrust[] tmp = new TodayEntrust[res.Length];
                int i = 0;
                foreach (QH_HistoryEntrustTableInfo e in res)
                {
                    TodayEntrust m = new TodayEntrust();
                    m.EntrustAmount = e.EntrustAmount;
                    m.EntrustNumber = e.EntrustNumber;
                    m.EntrustPrice = e.EntrustPrice;
                    m.EntrustTime = e.EntrustTime.ToString();
                    m.TradeAmount = e.TradeAmount;
                    m.TradeAveragePrice = e.TradeAveragePrice;
                    m.CancelAmount = e.CancelAmount;
                    m.IsMarketValue = e.IsMarketValue;
                    m.OrderMessage = e.OrderMessage;
                    m.OrderStatusId = e.OrderStatusId;
                    m.BuySellTypeId = e.BuySellTypeId;
                    m.SpotCode = e.ContractCode;
                    m.CloseFloatProfitLoss = e.CloseFloatProfitLoss;
                    m.CloseMarketProfitLoss = e.CloseMarketProfitLoss;
                    m.OpenCloseTypeId = e.OpenCloseTypeId;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货查询历史委托失败" + ex.Message, null, null);
                throw new Exception("股指期货查询历史委托失败", ex);
            }
        }

        [Remote("ifGetTodayTrade")]
        public TodayTradeResult getIfTodayTrade(string capitalAccount, string strPassword, int pageSize, int pageNo)
        {
            int count = 0;
            string strErrorMessage = "";
            FuturesTradeConditionFindEntity cond = new FuturesTradeConditionFindEntity();
            try
            {
                TodayTradeResult pagingRes = new TodayTradeResult();
                QH_TodayTradeTableInfo[] res = wcfService.queryIfTrade(out count, out strErrorMessage, capitalAccount, strPassword, pageNo, pageSize, cond);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                pagingRes.Total = count;
                TodayTrade[] tmp = new TodayTrade[res.Length];
                int i = 0;
                foreach (QH_TodayTradeTableInfo e in res)
                {
                    TodayTrade m = new TodayTrade();
                    m.SpotCode = e.ContractCode;
                    m.TradeTime = e.TradeTime.ToString();
                    m.TradePrice = e.TradePrice;
                    m.TradeAmount = e.TradeAmount;
                    m.TradeProceduresFee = e.TradeProceduresFee;
                    m.MarketProfitLoss = e.MarketProfitLoss;
                    m.OpenCloseTypeId = e.OpenCloseTypeId;
                    m.TradeTypeId = e.TradeTypeId;
                    m.BuySellTypeId = e.BuySellTypeId; 
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货查询当日成交失败" + ex.Message, null, null);
                throw new Exception("股指期货查询当日成交失败", ex);
            }
        }

        [Remote("ifGetHistoryTrade")]
        public TodayTradeResult getIfHistoryTrade(string capitalAccount, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            FuturesTradeConditionFindEntity cond = new FuturesTradeConditionFindEntity();
            try
            {
                TodayTradeResult pagingRes = new TodayTradeResult();
                QH_HistoryTradeTableInfo[] res = wcfService.queryIfHistoryTrade(out total, capitalAccount, pwd, cond, pageNo, pageSize, ref errorMsg);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                pagingRes.Total = total;
                TodayTrade[] tmp = new TodayTrade[res.Length];
                int i = 0;
                foreach (QH_HistoryTradeTableInfo e in res)
                {
                    TodayTrade m = new TodayTrade();
                    m.SpotCode = e.ContractCode;
                    m.TradeTime = e.TradeTime.ToString();
                    m.TradePrice = e.TradePrice;
                    m.TradeAmount = e.TradeAmount;
                    m.TradeProceduresFee = e.TradeProceduresFee;
                    m.MarketProfitLoss = e.MarketProfitLoss;
                    m.OpenCloseTypeId = e.OpenCloseTypeId;
                    m.TradeTypeId = e.TradeTypeId;
                    m.BuySellTypeId = e.BuySellTypeId;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货查询历史成交失败" + ex.Message, null, null);
                throw new Exception("股指期货查询历史成交失败", ex);
            }
        }

        [Remote("ifGetAccountHoldDetail")]
        public IfHoldResult getIfAccountHoldDetail(string capitalAccount, string strPassword, string stockCode, int buySellFlag, int pageSize, int pageNo)
        {
            FuturesHoldConditionFindEntity cond = new FuturesHoldConditionFindEntity();
            if (!string.IsNullOrEmpty(stockCode))
            {
                cond.ContractCode = stockCode;
            }
            if (buySellFlag > 0)
            {
                cond.BuySellDirectionId = buySellFlag;
            }

            int count = 0;
            int start = pageNo;
            int pageLength = pageSize;
            string strErrorMessage = "";

            try
            {
                IfHoldResult pagingRes = new IfHoldResult();
                FuturesHoldFindResultEntity[] res = wcfService.queryIfHold(out count, capitalAccount, strPassword, cond, pageNo, pageSize, ref strErrorMessage);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }

                pagingRes.Total = count;
                pagingRes.ResultList = res;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货查询持仓详细信息失败" + ex.Message, null, null);
                throw new Exception("股指期货查询持仓详细信息失败", ex);
            }
        }

        [Remote("ifGetCapital")]
        public XhDoQueryService.FuturesCapitalEntity getIfCapital(string strFundAccountId, string userPassword)
        {
            try
            {
                string strErrorMessage = "";
                XhDoQueryService.FuturesCapitalEntity res = wcfService.getIfCapital(strFundAccountId, XhDoQueryService.TypesCurrencyType.RMB, userPassword, ref strErrorMessage);
                decimal fee = 0M;
                if (res != null)
                {
                    //获得当日的交易费用，并保存在 RMBTodayOutInCapital 中
                    int count = 0;
                    FuturesTradeConditionFindEntity cond = new FuturesTradeConditionFindEntity();
                    QH_TodayTradeTableInfo[] res1 = wcfService.queryIfTrade(out count, out strErrorMessage, strFundAccountId, userPassword, 1, 200, cond);
                    if (res1 != null && res1.Length > 0)
                    {
                        foreach (QH_TodayTradeTableInfo r in res1)
                        {
                            fee += r.TradeProceduresFee;
                        }
                    }
                    res.RMBAvailableCapital = fee.ToString();
                } 
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货查询资产信息失败" + ex.Message, null, null);
                throw new Exception("股指期货查询资产信息失败", ex);
            }
        }

        [Remote("ifGetCapitalNew")]
        public DoCommonQuery.FuturesCapitalEntity getIfCapital2(string userId, string strFundAccountId, string userPassword)
        {
            try
            {
                string strErrorMessage = "";
                DoCommonQuery.FuturesCapitalEntity res = wcfService.getIfCapital2(userId, 6, DoCommonQuery.TypesCurrencyType.RMB, userPassword, ref strErrorMessage); ;
                decimal fee = 0M;
                if (res != null)
                {
                    //获得当日的交易费用，并保存在 RMBAvailableCapital 中
                    int count = 0;
                    FuturesTradeConditionFindEntity cond = new FuturesTradeConditionFindEntity();
                    QH_TodayTradeTableInfo[] res1 = wcfService.queryIfTrade(out count, out strErrorMessage, strFundAccountId, userPassword, 1, 200, cond);
                    if (res1 != null && res1.Length > 0)
                    {
                        foreach (QH_TodayTradeTableInfo r in res1)
                        {
                            fee += r.TradeProceduresFee;
                        }
                    }
                    res.RMBAvailableCapital = fee.ToString();
                }
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("股指期货查询资产信息失败" + ex.Message, null, null);
                throw new Exception("股指期货查询资产信息失败", ex);
            }
        }

    }

    class IfHoldResult
    {
        public int Total { get; set; }

        public FuturesHoldFindResultEntity[] ResultList { get; set; }
    }

    
}

